Brief Full Advanced Search Search Tips
|  |  | To access the contents, click the chapter and section titles. Visual Basic 6 Programming Blue Book: The Most Complete, Hands-On Resource for Writing Programs with Microsoft Visual Basic 6! (Publisher: The Coriolis Group) Author(s): Peter G. Aitken ISBN: 1576102815 Publication Date: 08/01/98 Search this book:
Previous | Table of Contents | Next
#### User-Defined Errors In addition to dealing with runtime errors, you can use Visual Basic’s error-handling capabilities to define your own errors. Two approaches are possible: raising errors that you define and returning errors from functions. Raising Your Own Errors The first approach is to assign an unused error number to an occurrence that you want to treat as an error. When the error condition occurs (as determined by your code), you use the Raise method to trigger the error and Visual Basic’s usual error-handling methods (OnError Goto, and Resume) to deal with it. Thus, a procedure could contain one error handler that deals with both “regular” system errors—such as disk drives not being ready—as well as your user-defined errors. Let’s try an example. Create a new project with a single form, placing the code in Listing 25.5 in the form’s Click event procedure. When you run the project and click on the form, you will be prompted to enter a name—any name, except “Bill”. If you follow instructions and enter, say, “Gladys”, you will be rewarded with a “Thank You” message. If you enter “Bill”, however, the If statement uses the Raise method to trigger an error with the Number 1234 and the Description “Not Bill, dummy!” The On Error Goto statement specifies that execution was to pass to the location identified by the label ErrorHandler. Code in the error handler checks to see if the error was the user-defined error identified by the Number property 1234. If so, the code displays a message consisting of the error’s Description property. Listing 25.5 Using the Raise method to generate user-defined errors.
    Private Sub Form_Click()

    Dim buf As String

    On Error GoTo ErrorHandler

    GetData:

    buf = InputBox(“Enter any name except 'Bill'.”)
    If buf = “Bill” Then Err.Raise 1234, , “Not Bill, dummy!”

    MsgBox (“Thank you”)

    Exit Sub

    ErrorHandler:

    If Err = 1234 Then
        MsgBox (Err.Description)
        Resume GetData
    End If

    End Sub
Error numbers from 0 to 1000 are reserved for use by Visual Basic (although not all of them are actually used). In regular code—code that is not in a class module—you can use any number between 1001 and 65535. When raising an error in a class module, you must add your error code number to the vbObjectError constant. For example, if the previous code were in a class module, you would write the following:
    If buf = “Bill” Then Err.Raise vbObjectError + 1234, , “Not Bill, dummy!”
Returning Errors From Functions The second approach to user-defined errors allows you to return an error value from a function. By returning an error value rather than the normal return value, you can signal the calling code that an error has occurred within the function. But how do you distinguish an error value from a nonerror value? The technique makes use of the flexibility of the Variant data type. Recall from Chapter 4 that a Variant can hold a variety of subtypes of data—one of which is Error. To convert a “regular” number into a type Error, you use the CVErr function. Thus, if X and Y are both type Variant variables, the code
    X = 1234
    Y = CVErr(1234)
results in X containing a subtype Integer and Y containing a subtype Error. Both have the same numerical value, but the subtype is different. You can tell if a Variant contains an Error subtype with the IsError function. When passed a type Variant, this function returns True if the subtype is Error; otherwise, it returns False. Listing 25.6 shows an example of using this type of user-defined error. Two procedures are included here: one is a general function; the other is the Click event procedure for the project’s form. When you run the project (assuming you know enough by now to create a new project and add these procedures on your own), click on the form, and the program will prompt you for a number. Your entry is passed to the SquareRoot function, and the following steps occur: 1. IsNumeric (one of Visual Basic’s built-in functions) tests whether the value you entered is a number. If it is not, then CVErr is used to pass back a type Error with the value 1002 as the function’s return value. 2. If the value is a number, check to see that it is not negative. (You may recall from high school algebra that negative numbers do not have square roots.) If the value is negative, then CVErr is used to pass back a type Error with the value 1001 as the function’s return value. 3. If the value passes these tests, it must be a non-negative number. You can take its square root and return the answer as a regular number. It is now up to the calling program to test the value returned by the SquareRoot function to determine if an error has occurred. This is done in two stages. First, the IsError function is used to determine if the return value is type Error. If it is not, the function returns a valid answer, and you can display it. If an Error is returned, the next step is testing the value that was returned to determine which type of error occurred. Note that you use the CInt function to convert the type Error value into a plain type Integer before comparing it with the constants 1001 and 1002. You could also have written the following, and it would work just as well:
    If answer = CVErr(1002) Then
Listing 25.6 Returning a type Error from a function.
    Public Function SquareRoot(X As Variant)

    If Not IsNumeric(X) Then
        SquareRoot = CVErr(1001)
    ElseIf X < 0 Then
        SquareRoot = CVErr(1002)
    Else
        SquareRoot = X ^ 0.5
    End If

    End Function

    Private Sub Form_Click()

    Dim num As Variant, answer As Variant

    num = CVar(InputBox(“Enter number for square root:”))
    answer = SquareRoot(num)
    If IsError(answer) Then
        If CInt(answer) = 1002 Then
            MsgBox (“Positive numbers only, please!”)
            Exit Sub
        End If
        If CInt(answer) = 1001 Then
            MsgBox (“That's not a number!”)
            Exit Sub
        End If
    End If

    MsgBox (“The square root of ” & num & “ is ” & answer)

    End Sub
#### General Error-Handling Code As I mentioned earlier, explicitly testing for every individual error that might conceivably occur in each procedure is not practical. Does this mean you can just ignore other errors? Not necessarily. You may not be able to explicitly handle an unexpected error, but at least you can inform the users of the nature of the error, so they can report it to you, permitting you to fix the problem in the code. The goal is to provide information about the nature of the error and where it occurred—both in terms of which form and which procedure it is in. You can obtain the name of the form from the property Screen.ActiveForm.Name. As for determining the procedure, declare a string variable and load it with the procedure name. An example is shown in Listing 25.7. Listing 25.7 Code for reporting information on untrapped errors.
    Dim ProcName As String
    ProcName = “Form_DblClick”

    On Error GoTo ErrorHandler

    ' Other code here

    ErrorHandler:

    msg = “An untrapped error has occurred. Please make a ” & VbCRLF
    msg = msg & “note of the following information.” & VbCRLF & VbCRLF
    msg = msg & “Error number: ” & Err.Number & VbCRLF
    msg = msg & “Description: ” & Err.Description & VbCRLF
    msg = msg & “Location: ” & Screen.ActiveForm.Name & VbCRLF
    msg = msg & “Procedure: ” & ProcName
    MsgBox (msg)
Perhaps more than any other aspect of a Visual Basic Program, the burden for well-designed error handling rests on the programmer. There are no clever controls that you can “drop in” to do the job for you. The errors that need to be addressed and the way they are handled will depend to a large degree on the specifics of your program. It’s tempting to skimp on error handling or to leave it for the end of the project. Wrong! Keep error handling in mind from the start, building it right into your program—not tacking it on at the end. You’ll save time and grief in the long run. Trust me on this—I know from experience.
Previous | Table of Contents | Next

| Products |